<template>
  <div class="VIDEO_COM">
    <!-- 在本组件中定义一个复用模板 -->
    <DefineTemplate v-slot="{item}">
      <div class="nameItem">
        <FlexAuto3>
          <div class="single-line-ellipsis">
            {{item.label}}
          </div>
        </FlexAuto3>
        <el-button
          text
          icon="Delete"
          type="danger"
          v-if="checkAuths(['del']) && comFileList.length>1"
          @click.stop="deleteItem(item)"
        ></el-button>
      </div>
    </DefineTemplate>
    <div>
      <ElSelectPlus
        v-model="selectFileName"
        :options="comFileList.map(i=> {return {value: i.fileName,label: i.fileName}})"
        @change="openFileSetRoute"
        filterable
      >
        <template #default="item">
          <!-- 可多次使用复用模板 -->
          <ReuseTemplate
            :item="item"
          />
        </template>
      </ElSelectPlus>
    </div>
    <div>
      倍数：<el-input-number
        v-model="playbackRate"
        :min="0.5"
        :max="16"
        :step="0.25"
      ></el-input-number>
    </div>
    <div class="showVideo">
      <XplayerVideo
        :src="getSrc()"
        :title="openFileFullPath"
        v-model:playback-rate="playbackRate"
        v-model:fullscreen="fullscreen"
        v-model:cssfullscreen="cssfullscreen"
        @loadeddata="loadeddata"
        @ended="ended"
        @pause="pause"
        @timeupdate="timeUpdate"
        ref="XplayerVideoRef"
      >
        <template #TopPosUIToVueUi>
          <div class="TopPosUIToVueUi" ref="TopPosUIToVueUiEl">
            <div class="left">
              <div>
                {{nowTime}}
              </div>
              <div>
                {{openFileFullPath}}
              </div>
              <div>
                <el-button
                  v-for="item in fastForwardList"
                  :key="'fastForwardList'+item"
                  type="text"
                  @click="fastForwardClick(item)"
                >
                  >>{{item}}
                </el-button>
              </div>
            </div>
            <ElSelectPlus
              v-if="fullscreen || cssfullscreen"
              :teleported="false"
              :fit-input-width="false"
              @visible-change="visibleChange"
              v-model="selectFileName"
              :options="comFileList.map(i=> {return {value: i.fileName,label: i.fileName}})"
              @change="openFileSetRoute"
            >
              <template #default="item">
                <!-- 可多次使用复用模板 -->
                <ReuseTemplate
                  :item="item"
                />
              </template>
            </ElSelectPlus>
          </div>
        </template>
      </XplayerVideo>
    </div>
  </div>
</template>

<script lang="ts">
import {CommonPropsMixin} from "@/views/dashboard/CommonPropsMixin";
import fileReq from "@/api/file.js";
import pathBrowserify from "path-browserify";
import {PathUtils} from "@/utils/PathUtils.ts";
import ElSelectPlus from "@/components/ElSelectPlus/index.vue";
import {ElMessageBox} from "element-plus";
import {useUserStore} from "@/store/modules/user.ts";
import XplayerVideo from "@/components/XplayerVideo/XplayerVideo.vue";
import {TimeUtils} from "@/utils/TimeUtils.ts";
import FlexAuto3 from "@/components/FlexAuto3.vue";
import {useTemplate} from "@/hooks/useTemplate.ts";
const [DefineTemplate, ReuseTemplate] = useTemplate();

export default {
  name: "MP4COM",
  components: {
    FlexAuto3, XplayerVideo, ElSelectPlus,
    DefineTemplate,
    ReuseTemplate,
  },
  mixins: [CommonPropsMixin],
  data() {
    return {
      selectFileName: '',
      useUserStore,
      isEnded: false,
      fullscreen: false,
      cssfullscreen: false,
      nowTime: '',
      seekTime: 0,
      clear: null,
      delListFile: [],
      fastForwardList: [
        13,88,15,90
      ]
    }
  },
  watch: {
    openFile: {
      immediate: true,
      handler(val) {
        if(val) {
          this.selectFileName=val
        }
      }
    },
  },
  created() {
    this.clear = setInterval(()=>{
      this.nowTime = TimeUtils.parseTime(new Date())
    },1000)
  },
  beforeUnmount() {
    clearInterval(this.clear)
    this.pause()
  },
  computed: {
    comFileList() {
      return this.fileList.filter(i=>".mp4" === PathUtils.extName(i.fileName).toLowerCase())
    },
    playbackRate: {
      get(){
        return useUserStore().userSysConfig.video.playbackRate
      },
      set(val) {
        if(val) {
          useUserStore().userSysConfig.video.playbackRate = val
        }
      }
    }
  },
  methods: {
    ended() {
      this.isEnded = true
      this.nextBtnClick()
    },
    nextBtnClickBefore() {
      this.isEnded = true
      return true
    },
    lastBtnClickBefore() {
      this.isEnded = true
      return true
    },
    loadeddata() {
      this.$nextTick(()=>{
        if(this.$refs.XplayerVideoRef){
          if(this.isEnded) {
            this.$refs.XplayerVideoRef.play()
            this.isEnded = false
          }
          if(this.delListFile.length) {
            fileReq.deleteFileOrDir(this.delListFile).then(res=>{
              this.refreshFileList()
            })
            this.delListFile = []
          }
        }
      })
      // 查询历史记录
      const historyList = useUserStore().userSysConfig.video.historyList;
      let find = historyList.find(i=>i.path === this.openFileFullPath)
      if(find) {
        ElMessageBox.confirm(`存在历史记录是否跳转？`,'提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info',
          appendTo: this.fullscreen?this.$refs.TopPosUIToVueUiEl:undefined
        }).then(()=>{
          this.$refs.XplayerVideoRef.seek(find.time)
        })
      }
    },
    fastForwardClick(item){
      this.$refs.XplayerVideoRef.seek(this.seekTime + item)
    },
    getSrc() {
      return fileReq.getGetUrl(pathBrowserify.resolve(this.baseFilePath,this.openFile))
    },
    visibleChange(visible: boolean) {
      this.$refs.XplayerVideoRef.focus({
        autoHide: !visible,
      })
    },
    deleteItem(item){
      let delList = [
        PathUtils.resolve(this.baseFilePath,item.label)
      ]
      ElMessageBox.confirm(`${item.label}是否确认删除？`,'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        appendTo: this.fullscreen?this.$refs.TopPosUIToVueUiEl:undefined
      }).then(()=>{
        if(this.openFile === item.label) {
          this.nextBtnClick()
          this.delListFile = delList
        } else {
          fileReq.deleteFileOrDir(delList).then(res=>{
            this.refreshFileList()
          })
        }
      })
    },
    pause() {
      // 记录历史
      useUserStore().pushVideoHistory({
        time: this.seekTime,
        path: this.openFileFullPath
      })
    },
    timeUpdate(params) {
      this.seekTime = params.currentTime
    }
  },
}
</script>

<style lang="scss" scoped src="./VIDEO_COM.scss"></style>
